package com.zhuoli.service.springboot.jdbctemplate.repository.service.impl;

import com.zhuoli.service.springboot.jdbctemplate.repository.model.User;
import com.zhuoli.service.springboot.jdbctemplate.repository.service.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: zhuoli
 * @Date: 2018/8/2 10:51
 * @Description:
 */
@Repository
@AllArgsConstructor
public class UserRepositoryImpl implements UserRepository {
    private final JdbcTemplate jdbcTemplate;

    @Override
    public List<User> getAllUsers() {
        String sql = "select * from user";
        return jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public User getUserById(Long id) {
        String sql = "select * from user where id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public int delUserById(Long id) {
        String sql = "UPDATE user SET is_deleted = 1 WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public int createUser(User user) {
        String sql = "insert into user(user_name, description, is_deleted) values(?, ?, 0)";
        return jdbcTemplate.update(sql, user.getUserName(), user.getDescription());
    }

    @Override
    public int updateUser(User user) {
        String sql = "UPDATE user SET user_name = ? ,description = ? WHERE id = ?";
        return jdbcTemplate.update(sql, user.getUserName(), user.getDescription(), user.getId());
    }
}
